import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../core/base/base_view_model.dart';
import 'role_model.dart';
import 'role_view_model.dart';
import 'dialogs/role_edit_dialog.dart';
import 'role_permissions/role_permissions_view.dart';

class RoleListView extends StatelessWidget {
  const RoleListView({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (_) => RoleViewModel(),
      child: const _RoleListViewContent(),
    );
  }
}

class _RoleListViewContent extends StatefulWidget {
  const _RoleListViewContent({Key? key}) : super(key: key);

  @override
  _RoleListViewContentState createState() => _RoleListViewContentState();
}

class _RoleListViewContentState extends State<_RoleListViewContent> {
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      context.read<RoleViewModel>().fetchRoles();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('角色管理'),
        actions: [
          IconButton(
            icon: const Icon(Icons.add),
            onPressed: () => _showRoleEditDialog(context),
          ),
        ],
      ),
      body: Consumer<RoleViewModel>(
        builder: (context, viewModel, child) {
          if (viewModel.state == ViewState.busy) {
            return const Center(child: CircularProgressIndicator());
          }

          if (viewModel.state == ViewState.error) {
            return Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    viewModel.errorMessage ?? '未知错误',
                    style: const TextStyle(color: Colors.red),
                  ),
                  const SizedBox(height: 16),
                  ElevatedButton(
                    onPressed: () => viewModel.fetchRoles(),
                    child: const Text('重试'),
                  ),
                ],
              ),
            );
          }

          return ListView.builder(
            itemCount: viewModel.roles.length,
            itemBuilder: (context, index) {
              final role = viewModel.roles[index];
              return Card(
                margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                child: ListTile(
                  title: Text(role.name),
                  subtitle: Text(role.remark),
                  trailing: Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      IconButton(
                        icon: const Icon(Icons.edit),
                        onPressed: () => _showRoleEditDialog(context, role: role),
                      ),
                      IconButton(
                        icon: const Icon(Icons.security),
                        onPressed: () => Navigator.of(context).push(
                          MaterialPageRoute(
                            builder: (context) => RolePermissionsView(
                              roleId: role.id,
                              roleName: role.name,
                            ),
                          ),
                        ),
                      ),
                      IconButton(
                        icon: const Icon(Icons.delete),
                        onPressed: () => _showDeleteConfirmDialog(context, role),
                      ),
                    ],
                  ),
                ),
              );
            },
          );
        },
      ),
    );
  }

  Future<void> _showRoleEditDialog(BuildContext context, {Role? role}) async {
    final result = await showDialog<bool?>(
      context: context,
      builder: (context) => RoleEditDialog(role: role),
    );

    if (result == true) {
      if (mounted) {
        context.read<RoleViewModel>().fetchRoles();
      }
    }
  }

  Future<void> _showDeleteConfirmDialog(BuildContext context, Role role) async {
    final confirmed = await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('确认删除'),
        content: Text('确定要删除角色"${role.name}"吗？'),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(false),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () => Navigator.of(context).pop(true),
            child: const Text('删除'),
          ),
        ],
      ),
    );

    if (confirmed == true && mounted) {
      await context.read<RoleViewModel>().deleteRole(role.id);
    }
  }
}